package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.audio.edit.AeConst;

import VideoHandle.EpAudio;
import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityAudioSpeedBinding;
import flc.ast.utils.Content;
import flc.ast.view.BaseAvTrackView;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class AudioSpeedActivity extends BaseAc<ActivityAudioSpeedBinding> implements IAudioPlayer.IListener {

    public static String audioPath;
    protected IAudioPlayer mAudioPlayer;
    private boolean isInitTrackViewDuration = false;
    private float mSpeed = 1.0f;
    private float mPitch = 1.0f;
    private String mAudioName;
    private Dialog myRenameDialog;
    private EditText editText;

    @Override
    protected int onCreate() {
        return R.layout.activity_audio_speed;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAudioSpeedBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.tvName.setOnClickListener(this);
        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.play(audioPath);
        mAudioPlayer.setListener(this);
        mDataBinding.ivAudioSpeedSave.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.trackView.setTrackBgColor(Color.parseColor("#1D2022"));
        mDataBinding.trackView.setListener(new BaseAvTrackView.IListener() {
            @Override
            public void onStartTimeChanged(long startTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) startTime);
                    mAudioPlayer.resume();
                }
            }

            @Override
            public void onEndTimeChanged(long endTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) endTime);
                    mAudioPlayer.resume();
                }
            }

            @Override
            public void onStartEndTimeChanged(long startTime, long endTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) startTime);
                    mAudioPlayer.resume();
                }
            }
        });
        mDataBinding.ivMinus1.setOnClickListener(this);
        mDataBinding.ivPlus1.setOnClickListener(this);
        mDataBinding.ivMinus2.setOnClickListener(this);
        mDataBinding.ivPlus2.setOnClickListener(this);

        mDataBinding.sbSpeed.setMax(AeConst.SPEED_MAX_PROGRESS);
        mDataBinding.sbSpeed.setProgress(AeConst.getProgressBySpeed(mSpeed));
        mDataBinding.sbSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser) {
                    return;
                }
                mSpeed = AeConst.getSpeedByProgress(progress);
                updateSpeedTxtValue();
                if (mAudioPlayer != null) {
                    mAudioPlayer.setSpeed(mSpeed);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mDataBinding.sbTone.setMax(AeConst.PITCH_MAX_PROGRESS);
        mDataBinding.sbTone.setProgress(AeConst.getProgressByPitch(mPitch));
        mDataBinding.sbTone.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser) {
                    return;
                }
                mPitch = AeConst.getPitchByProgress(progress);
                updatePitchTxtValue();
                if (mAudioPlayer != null) {
                    mAudioPlayer.setPitch(mPitch);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlay://播放
                if (mAudioPlayer == null) {
                    return;
                }
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                } else {
                    mAudioPlayer.resume();
                }
                break;
            case R.id.tvName://重命名
                myRenameDialog.show();
                break;
            //重命名
            case R.id.tvDialogRenameConfirm:
                String name = editText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                mAudioName = name;
                mDataBinding.tvName.setText(mAudioName + "." + FileUtils.getFileExtension(audioPath));
                myRenameDialog.dismiss();
                editText.setText("");
                break;
            case R.id.tvDialogRenameCancel:
                editText.setText("");
                myRenameDialog.dismiss();
                break;
            case R.id.ivMinus1://音速-
                clickSpeedMinusPlus(true);
                break;
            case R.id.ivPlus1://音速+
                clickSpeedMinusPlus(false);
                break;
            case R.id.ivMinus2://音调-
                clickPitchMinusPlus(true);
                break;
            case R.id.ivPlus2://音调+
                clickPitchMinusPlus(false);
                break;
            case R.id.ivAudioSpeedSave://保存
                save();
                break;
        }
    }

    @Override
    protected void initData() {
        mAudioName = FileUtils.getFileNameNoExtension(audioPath);
        mDataBinding.tvName.setText(FileUtils.getFileName(audioPath));
    }

    private void save() {
        String path = FileUtil.generateFilePath(Content.myTemp, ".mp3");
        showDialog(getString(R.string.saving));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                EpAudio epAudio = new EpAudio(audioPath);
                epAudio.setPitch(mPitch);
                epAudio.setTempo(mSpeed);
                EpEditor.audioExec(epAudio, path, new OnEditorListener() {
                    @Override
                    public void onSuccess() {
                        emitter.onNext(true);
                    }

                    @Override
                    public void onFailure() {
                        emitter.onNext(false);
                    }

                    @Override
                    public void onProgress(float progress) {

                    }
                });
            }

            @Override
            public void accept(Boolean result) {
                dismissDialog();
                if (result) {
                    FileP2pUtil.copyPrivateAudioToPublic(mContext, path);
                    ToastUtils.showShort(getString(R.string.save_success));
                    startActivity(HomeActivity.class);
                }
            }
        });

    }

    private void clickPitchMinusPlus(boolean isMinus) {
        float stepValue = AeConst.getPitchStepValue();
        mPitch += stepValue * (isMinus ? -1 : 1);
        if (mPitch < AeConst.PITCH_MIN) {
            mPitch = AeConst.PITCH_MIN;
        }
        if (mPitch > AeConst.PITCH_MAX) {
            mPitch = AeConst.PITCH_MAX;
        }
        updatePitchTxtValue();
        mDataBinding.sbTone.setProgress(AeConst.getProgressByPitch(mPitch));
        if (mAudioPlayer != null) {
            mAudioPlayer.setPitch(mPitch);
        }
    }

    private void clickSpeedMinusPlus(boolean isMinus) {
        float stepValue = AeConst.getSpeedStepValue();
        mSpeed += stepValue * (isMinus ? -1 : 1);
        if (mSpeed < AeConst.SPEED_MIN) {
            mSpeed = AeConst.SPEED_MIN;
        }
        if (mSpeed > AeConst.SPEED_MAX) {
            mSpeed = AeConst.SPEED_MAX;
        }
        updateSpeedTxtValue();
        mDataBinding.sbSpeed.setProgress(AeConst.getProgressBySpeed(mSpeed));
        if (mAudioPlayer != null) {
            mAudioPlayer.setSpeed(mSpeed);
        }
    }

    private void updatePitchTxtValue() {
        mDataBinding.tvToneValue.setText("+" + String.format("%.1f", mPitch));
    }

    private void updateSpeedTxtValue() {
        mDataBinding.tvSpeedValue.setText("x" + String.format("%.1f", mSpeed));
    }

    @Override
    public void onUpdatePlayTime(int curPlayTime, int duration) {
        if (!isInitTrackViewDuration) {
            isInitTrackViewDuration = true;
            mDataBinding.trackView.setDuration(duration);
        }
        mDataBinding.trackView.setPlayTime(curPlayTime);
    }

    @Override
    public void onPlayChange(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.ivPlay.setImageResource(R.drawable.abofzhong);
        } else {
            mDataBinding.ivPlay.setImageResource(R.drawable.azantinz);
        }
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogRenameConfirm);
        editText = inflate.findViewById(R.id.etDialogFormatRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAudioPlayer != null) {
            mAudioPlayer.resume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

}